<style lang="stylus" scoped>

</style>

<template>
  <div>
    <q-table
      class="bg-white shadow-1"
      :data="data"
      dense
      :columns="columns"
      row-key="id"
      separator="cell"
      :visible-columns="visibleColumns"
      :pagination.sync="pagination"
      selection="multiple"
      :selected.sync="selected"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-right="props">
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-if="searchToggle" v-slot:top-row="props">
        <q-tr :props="props">
          <q-td>
            <q-btn color="primary" dense flat icon="search"  @click="listGet({ pagination: pagination, filter: searchForm })"/>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
            <q-input dense outlined v-model="searchForm[col.name]"/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <!-- <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td> -->
          <!-- <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense> -->
                <!-- <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item> -->
                <!-- <q-item clickable v-close-popup @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item> -->
                <!-- <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item> -->
              <!-- </q-list>
            </q-btn-dropdown> -->
          <!-- </q-td> -->
          <q-td key="itemCode" :props="props">
            <span class="text-light-blue cursor-pointer" @click="distribution(props.row.itemId)">{{ props.row.itemCode  }}</span></q-td>
          <q-td key="itemName" :props="props">{{ props.row.itemName }}</q-td>
          <q-td key="siteCode" :props="props">{{ props.row.siteCode }}</q-td>
          <q-td key="siteName" :props="props">{{ props.row.siteName }}</q-td>
          <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>

  </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators'
export default {
  name: 'Site',
  props: {
    url: {},
    id: {}
  },
  data () {
    return {
      searchToggle: false,
      searchForm: {
        itemCode: '',
        itemName: '',
        siteCode: '',
        siteName: '',
        createUserName: '',
        createTime: ''
      },
      selected: [],
      visibleColumns: [
        'itemCode',
        'itemName',
        'siteCode',
        'siteName',
        'createUserName',
        'createTime'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        // { name: 'action', required: true, label: '操作', align: 'center' },
        { name: 'itemCode', required: true, label: '品项编码', align: 'left', field: 'itemCode', sortable: true },
        { name: 'itemName', required: true, label: '品项名称', align: 'left', field: 'itemName', sortable: true },
        { name: 'siteCode', required: true, label: '地点编码', align: 'left', field: 'siteCode', sortable: true },
        { name: 'siteName', required: true, label: '地点名称', align: 'left', field: 'siteName', sortable: true },
        { name: 'createUserName', field: 'createUserName', align: 'left', label: '创建人', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      // dialog
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      loadingSingleSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditTab: 'tab1',
      addOrEditForm: {
        name: '',
        nameEn: '',
        type: '',
        code: Number
      },
      // options
      options: []
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      code: { required },
      type: { required }
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination
      })
    },
    'id' () {
      this.listGet({
        pagination: this.pagination
      })
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.listGet({
        pagination: this.pagination
      })
    },
    distribution (id) {
      this.$router.push({
        name: 'Relationship',
        params: { id }
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: this.url,
        params: {
          categoryId: this.id,
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          ...filter,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : '')
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    async add () {
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        code: null,
        name: '',
        nameEn: '',
        type: ''
      }
      this.ticked = []
      this.$v.addOrEditForm.$reset()
      await this.optionsGet()
      this.addOrEditDialog = true
    },
    async edit (row) {
      await Promise.all([
        this.$api({
          method: 'get',
          url: `/mdm/site/findById/${row.id}`,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.addOrEditForm = { ...data }
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        }),
        this.optionsGet(),
        this.locationGet(row.id)
      ])
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/mdm/site/add' : '/mdm/site/update',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
        this.init()
      }
    },
    async saveSingleHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSingleSave = true
        await this.$api({
          method: 'put',
          url: '/mdm/site/add',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditForm = { ...data }
            this.addOrEdit = 2
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSingleSave = false
        this.init()
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除地点：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/site/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 权限数据 获取
    async optionsGet () {
      await this.$api({
        method: 'post',
        url: '/mdm/siteType/queryNoPage',
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.options = data
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async locationGet (id) {
      await this.$api({
        method: 'post',
        url: `/mdm/location/query/${id}`,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          // this.options = data
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    }
  }
}
</script>
